package com.gage.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.gage.commons.result.PageInfo;
import com.gage.mapper.CmsArticleMapper;
import com.gage.mapper.CmsCatalogMapper;
import com.gage.mapper.CmsMappingMapper;
import com.gage.model.CmsArticle;
import com.gage.model.CmsMapping;
import com.gage.service.ICmsArticleService;

@Service
public class CmsArticleServiceImpl implements ICmsArticleService{
	@Autowired
	public CmsArticleMapper cmsArticleMapper;
	@Autowired
	public CmsMappingMapper cmsMappingMapper;
	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int insertSelective(CmsArticle article) {
		int count=0;
		count= cmsArticleMapper.insertSelective(article);
		String[] catalogIds=article.getCatalogIds().split(",");
		String articleId=article.getId().toString();
		CmsMapping cmsmapping=new CmsMapping();
		for (int i = 0; i < catalogIds.length; i++) {
			cmsmapping.setArticleid(articleId);
			cmsmapping.setCatalogid(catalogIds[i]);
			cmsMappingMapper.insertSelective(cmsmapping);
		}
		return count;
	}

	@Override
	public CmsArticle selectByPrimaryKey(Integer id) {
		return cmsArticleMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(CmsArticle article) {
		String[] catalogIds=article.getCatalogIds().split(",");
		String articleId=article.getId().toString();
		cmsMappingMapper.deleteByArticleid(articleId);
		CmsMapping cmsmapping=new CmsMapping();
		for (int i = 0; i < catalogIds.length; i++) {
			cmsmapping.setArticleid(articleId);
			cmsmapping.setCatalogid(catalogIds[i]);
			cmsMappingMapper.insertSelective(cmsmapping);
		}
		return cmsArticleMapper.updateByPrimaryKeySelective(article);
	}

	@Override
	public PageInfo selectDataGrid(PageInfo pageInfo) {
		  Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageInfo.getNowpage(), pageInfo.getSize());
	        page.setOrderByField(pageInfo.getSort());
	        page.setAsc(pageInfo.getOrder().equalsIgnoreCase("asc"));
	        List<Map<String, Object>> list = cmsArticleMapper.selectArticleByStr(page, pageInfo.getCondition());
	        pageInfo.setRows(list);
	        pageInfo.setTotal(page.getTotal());
	        return pageInfo;
	}

	@Override
	public Integer deleteByIds(List<String> ids) {
		for (int i = 0; i < ids.size(); i++) {
			 cmsMappingMapper.deleteByArticleid(ids.get(i));
		}
		return cmsArticleMapper.deleteByIds(ids);
	}

	@Override
	public List<String> selectCatalogByArticleId(String articleId) {
		return cmsMappingMapper.selectCatalogByArticleId(articleId);
	}

}
